class SpringChain2 extends egret.Sprite {
    private balls: Array<Ball>
    private numBalls: number = 4

    private spring: number = 0.1
    private targetX: number = 0
    private targetY: number = 0
    private friction: number = 0.80
    private gravity: number = 3

    public constructor() {
        super()

        this.once(egret.Event.ADDED_TO_STAGE, this.onAddToStage, this)
    }

    private onAddToStage(event: egret.Event) {
        this.targetX = this.stage.stageWidth / 2
        this.targetY = this.stage.stageHeight / 2

        this.balls = new Array<Ball>()
        for (let i = 0; i < this.numBalls; ++i) {
            let ball = new Ball(20)
            this.addChild(ball)
            this.balls.push(ball)
        }

        this.stage.addEventListener(egret.TouchEvent.TOUCH_MOVE, this.trackTouch, this)
        this.addEventListener(egret.Event.ENTER_FRAME, this.onEnterFrame, this)
    }

    private onEnterFrame(event: egret.Event) {
        let targetX = this.targetX
        let targetY = this.targetY
        
        this.graphics.clear()
        this.graphics.lineStyle(1)
        this.graphics.moveTo(this.targetX, this.targetY)
        for (let i = 0; i < this.balls.length; ++i) {
            this.graphics.lineTo(this.balls[i].x, this.balls[i].y)
            this.moveBall(this.balls[i], targetX, targetY)
            targetX = this.balls[i].x
            targetY = this.balls[i].y
        }
   }

    private moveBall(ball: Ball, targetX: number, targetY: number) {
        let dx = targetX - ball.x
        let dy = targetY - ball.y
        let ax = dx * this.spring
        let ay = dy * this.spring
        ball.vx += ax
        ball.vy += ay
        ball.vy += this.gravity
        ball.vx *= this.friction
        ball.vy *= this.friction
        ball.x += ball.vx
        ball.y += ball.vy
    }

    private trackTouch(evt: egret.TouchEvent) {
        this.targetX = evt.stageX
        this.targetY = evt.stageY
    }
}